//
//  YXNetWorkTool.swift
//  yanXiangWeiBo
//
//  Created by 颜祥 on 15/12/19.
//  Copyright © 2015年 yanxiang. All rights reserved.
//

import UIKit
import AFNetworking

class YXNetWorkTool: AFHTTPSessionManager
{
    // MARK: - 创建网络工具单例
    static let sharedInstance: YXNetWorkTool =
    {
        // url
        let baseURL = NSURL(string: "https://api.weibo.com/")
        
        let tool = YXNetWorkTool(baseURL: baseURL)
        
        // 服务器会报错:Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain",由于服务器不能识别text/plain格式
        // 设置反序列化数据格式集合
        tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String>
        
        
        return tool
    
    }()
    
    /*
    
    App Key：1650671964
    App Secret：cde53e712ff09cb5bd24830c8580e6fe
    App Key是应用的唯一标识，开放平台通过App Key来鉴别应用的身份。AppSecret是给应用分配的密钥，开发者需要妥善保存这个密钥，这个密钥用来保证应用来源的的可靠性，防止被伪造。
    */
    
    // MARK: - 授权相关
    // app key 申请应用时分配的AppKey
    // AppKey:3912320572
    //private let client_id = "1650671964"
     private let client_id = "3912320572"
    
    // 授权回调地址,回调地址，需需与注册应用里的回调地址一致
     let redirect_uri = "http://www.baidu.com/"
    
    // app 秘钥,申请应用时分配的AppSecret
    // Secret：a4b1682877e09503f6c91e632f1240a5
    //private let client_secret = "cde53e712ff09cb5bd24830c8580e6fe"
    private let client_secret = "a4b1682877e09503f6c91e632f1240a5"
    
    // 拼接登录界面URL
    func oAuthURL() -> NSURL
    {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    

    // 当加载accseeeToken完成后，要告诉调用者加载完成后的结果，加载成功或失败，并回传结果,将获得的accessToken回传给调用者
    /*
    result:Optional({
    "access_token" = "2.00r3G2zB3LDinB915be41466ucAiVB";
    "expires_in" = 157679999;
    "remind_in" = 157679999;
    uid = 1822518697;
    })
    
    */
    // MARK: - 加载accessToken
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ())
    {
        // 1.准备url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.准备参数parameters--字典
        let parameters = [
        
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 3.请求数据----POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            // print("result:\(result)")
            // 执行闭包，回传数据请求的结果
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                
            print("error:\(error)")
            // 将错误回调
            finished(result: nil, error: error)
                
        }
    }
    
    // MARK: - 加载用户信息
    func loadUserInfo(finished:(result: [String: AnyObject]?, error: NSError?) -> ())
    {
        // 1.获取accessToken
        guard let access_token = YXUserAccount.loadUserAccount()?.access_token else
        {
            // 能到这里说明access_token没有值
            print("access_token没有值")
            return
        }
        
        // 2.获取uid
        guard let uid = YXUserAccount.loadUserAccount()?.uid else
        {
            print("uid没有值")
            return
        }
        
        // 3.获得url
        let URLString = "https://api.weibo.com/2/statuses/user_timeline.json"
        
        let parameters = [
        
            "access_token": access_token,
            "uid": uid
        
        ]
        
        
        // 4.发送GET请求
        GET(URLString, parameters: parameters, success: { (_, result) -> Void in
            // 调用准备好的闭包
            print("result: \(result)")
            let dict = result as? [String: AnyObject]
            
            finished(result: dict, error: nil)
            
            
            }) { (_, error) -> Void in
                
            print("error: \(error)")
            finished(result: nil, error: error)
                
        }
        
    }
    
    
    
    
  
}
